package com.usian.user.service.ImpI;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.feign.WemediaFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserRealnameService;
import com.usian.user.service.ApUserService;
import com.usian.utils.common.AppJwtUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserRealnameService apUserRealnameService;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Autowired
    private WemediaFeign wemediaFeign;


    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto) {
        //校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //校验状态
        if (dto.getStatus() != 2 && dto.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //更新状态

        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(dto.getStatus());
        //如果状态==2 错误信息不等于空 把未通过审核的原因赋值给他
        if (dto.getStatus() == 2 || dto.getMsg() != null) {
            apUserRealname.setReason(dto.getMsg());
        }
        apUserRealnameService.updateById(apUserRealname);

        //远程调用获取对象ap_user表的
        ApUserRealname realname = apUserRealnameService.getById(dto.getId());
        ApUser apUser = this.getById(realname.getUserId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断审核是否成功
        if (dto.getStatus() == 9) {
            //远程保存调用自媒体
            //查询自媒体账号是否存在 如果存在不保存 不存在则保存
            WmUser wmUser = wemediaFeign.findByName(apUser.getName());
            if (wmUser == null) {
                wmUser = new WmUser();
                //设置ApUserId
                wmUser.setApUserId(apUser.getId());
                wmUser.setCreatedTime(new Date());
                wmUser.setSalt(apUser.getSalt());
                wmUser.setName(apUser.getName());
                wmUser.setPassword(apUser.getPassword());
                wmUser.setStatus(9);
                wmUser.setPhone(apUser.getPhone());
                wemediaFeign.saveWmUser(wmUser);
            }

            /***
             * 保存作者信息 判断作者是否存在 存在不保存 不存在则保存
             */
            ApAuthor author = apAuthorFeign.findByUserId(apUser.getId());
            if (author == null) {
                ApAuthor apAuthor = new ApAuthor();
                apAuthor = new ApAuthor();
                apAuthor.setName(wmUser.getName());
                apAuthor.setType(2);
                apAuthor.setCreatedTime(new Date());
                apAuthor.setUserId(apUser.getId());
                apAuthor.setWmUserId(wmUser.getId());
                apAuthorFeign.saveAuthor(apAuthor);
            }


        }

        /***
         * 修改ap_user表中flag状态
         */

        apUser.setFlag((short) 1);

        this.updateById(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /***
     * login
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.参数校验
        if ((StringUtils.isEmpty(dto.getPhone()) || StringUtils.isEmpty(dto.getPassword())) && dto.getEquipmentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "手机号或密码不能为空");
        }

        if ((StringUtils.isEmpty(dto.getPhone()) || StringUtils.isEmpty(dto.getPassword()))) {
            //根据设备生成token 以0生成
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        } else {
            //根据账号生成token
            QueryWrapper<ApUser> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(ApUser::getPhone, dto.getPhone());
            List<ApUser> list = list(wrapper);
            if (list != null && list.size() == 1) {
                ApUser apUser = list.get(0);
                String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                if (apUser.getPassword().equals(pwd)) {
                    Map<String, Object> map = Maps.newHashMap();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user", apUser);
                    return ResponseResult.okResult(map);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        }
    }
}
